package com.example.a1.fannong;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.IdRes;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.view.View;
import android.widget.FrameLayout;

import com.example.a1.fannong.core.app.BaseActivity;
import com.example.a1.fannong.core.app.BaseFragment;
import com.example.a1.fannong.core.app.MyApplication;
import com.example.a1.fannong.core.http.OnResultListener;
import com.example.a1.fannong.core.manager.user.OnUserStateChangeListener;
import com.example.a1.fannong.core.manager.user.UserManager;
import com.example.a1.fannong.core.manager.version.VersionManager;
import com.example.a1.fannong.model.VersionInfo;
import com.example.a1.fannong.ui.main.CentreFragment;
import com.example.a1.fannong.ui.main.ClassifyFragment;
import com.example.a1.fannong.ui.main.HomeFragment;
import com.example.a1.fannong.ui.main.MineFragment;
import com.example.a1.fannong.ui.main.ShoppingCartFragment;
import com.example.a1.fannong.view.MainTabItem;

import cn.personal.library.viewinject.FindViewById;
import cn.personal.library.viewinject.OnClick;
import cn.personal.library.viewinject.ViewInjecter;

/**
 * 基本主页
 */
public class MainActivity extends BaseActivity {

    public static final String KEY_ACTION = "key_action";
    public static final String ACTION_CHANGE_TAB = "action_change_tab";
    public static final String ACTION_START_LOGIN = "action_start_login";
    public static final String KEY_ACTION_CHANGE_TAB_ID = "key_action_change_tab_id";

    @FindViewById(R.id.main_tab_item_1)
    protected MainTabItem tabItem1;

    @FindViewById(R.id.main_tab_item_2)
    protected MainTabItem tabItem2;

    @FindViewById(R.id.main_tab_item_3)
    protected MainTabItem tabItem3;

    @FindViewById(R.id.main_tab_item_4)
    protected MainTabItem tabItem4;

    @FindViewById(R.id.main_tab_item_5)
    protected MainTabItem tabItem5;

    @FindViewById(R.id.main_content_container)
    FrameLayout container;

    private MainTabItem[] tabItems;

    private long lastPressedBackTime = System.currentTimeMillis() - 20000;

    @MyApplication.Manager
    private UserManager userManager;

    @MyApplication.Manager
    private VersionManager versionManager;

    OnUserStateChangeListener onUserStateChangeListener = new OnUserStateChangeListener() {
        @Override
        public void onUserLogin() {

        }

        @Override
        public void onUserLogout() {
            finish();
        }
    };


    public static void startMainActivity(Context context) {
        Intent intent = new Intent();
        intent.setClass(context, MainActivity.class);
        context.startActivity(intent);
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(null);
        setContentView(R.layout.activity_main);
        ViewInjecter.inject(this);

        tabItems = new MainTabItem[5];
        tabItems[0] = tabItem1;
        tabItems[1] = tabItem2;
        tabItems[2] = tabItem3;
        tabItems[3] = tabItem4;
        tabItems[4] = tabItem5;
        initTabView();

        checkType();
        getIntentData(getIntent());
        userManager.addOnUserStateChangeListener(onUserStateChangeListener);
        versionManager.checkUpdate(new OnResultListener<VersionInfo>() {
            @Override
            public void onResult(int result, String msg, VersionInfo versionInfo) {
                if (versionInfo != null) {
                   // UpdateActivity.startActivity(getContext(), versionInfo);
                }
            }
        });

    }

    @Override
    public void finish() {
        super.finish();
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        getIntentData(intent);
    }

    private void getIntentData(final Intent intent) {
        MyApplication.HANDLER.post(new Runnable() {
            @Override
            public void run() {
                handlerIntentData(intent);
            }
        });
    }

    private void handlerIntentData(Intent intent) {
        String action = intent.getStringExtra(KEY_ACTION);
        if (action != null) {
            if (action.equals(ACTION_CHANGE_TAB)) {
                int tabId = intent.getIntExtra(KEY_ACTION_CHANGE_TAB_ID, R.id.main_tab_item_1);
                selectTabItem(tabId);
            } else if (action.equals(ACTION_START_LOGIN)) {
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        userManager.removeOnUserStateChangeListener(onUserStateChangeListener);
    }

    private void checkType() {
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        Fragment fragment = getSupportFragmentManager().findFragmentByTag(tabItem1.getId() + "");
        if (fragment != null) {
            transaction.remove(fragment);
        }
        fragment = getSupportFragmentManager().findFragmentByTag(tabItem2.getId() + "");
        if (fragment != null) {
            transaction.remove(fragment);
        }
        fragment = getSupportFragmentManager().findFragmentByTag(tabItem3.getId() + "");
        if (fragment != null) {
            transaction.remove(fragment);
        }
        fragment = getSupportFragmentManager().findFragmentByTag(tabItem4.getId() + "");
        if (fragment != null) {
            transaction.remove(fragment);
        }

        transaction.commitAllowingStateLoss();

        for (MainTabItem tabItem : tabItems) {
            if (tabItem.isTabSelected()) {
                tabItem.setIsSelected(false);
            }
        }

        //默认选中首页
        MyApplication.HANDLER.post(new Runnable() {
            @Override
            public void run() {
                selectTabItem(R.id.main_tab_item_1);
            }
        });
    }

    @OnClick({R.id.main_tab_item_1,
            R.id.main_tab_item_2,
            R.id.main_tab_item_3,
            R.id.main_tab_item_4,
            R.id.main_tab_item_5})
    public void onTabClick(View view) {
        selectTabItem(view.getId());
    }

    public void selectTabItem(@IdRes int tabId) {
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        for (MainTabItem tabItem : tabItems) {
            if (tabItem.getId() == tabId) {
                if (!tabItem.isTabSelected()) {
                    tabItem.setIsSelected(true);
                    BaseFragment fragment = (BaseFragment) getSupportFragmentManager().findFragmentByTag(tabId + "");
                    if (fragment == null) {
                        fragment = createFragment(tabId);
                        transaction.add(R.id.main_content_container, fragment, tabId + "");
                    } else {
                        transaction.show(fragment);
                    }
                }
            } else {
                if (tabItem.isTabSelected()) {
                    tabItem.setIsSelected(false);
                    BaseFragment fragment = (BaseFragment) getSupportFragmentManager().findFragmentByTag(tabItem.getId() + "");
                    if (fragment != null) {
                        transaction.hide(fragment);
                    }
                }
            }
        }
        transaction.commitAllowingStateLoss();
    }

    public BaseFragment createFragment(int tab) {
        BaseFragment fragment;
        switch (tab) {
            case R.id.main_tab_item_1:
                fragment = new HomeFragment();
                break;
            case R.id.main_tab_item_2:
                fragment = new ClassifyFragment();
                break;
            case R.id.main_tab_item_3:
                fragment = new CentreFragment();
                break;
            case R.id.main_tab_item_4:
                fragment = new ShoppingCartFragment();
                break;
            case R.id.main_tab_item_5:
                fragment = new MineFragment();
                break;
            default:
                throw new RuntimeException("不支持的tab类型，请检查参数");
        }
        return fragment;
    }

    protected void initTabView() {
    };

    @Override
    public void onBackPressed() {
        if (!tabItem1.isTabSelected()) {
            selectTabItem(R.id.main_tab_item_1);
            return;
        }

        if (System.currentTimeMillis() - lastPressedBackTime < 2000) {
            super.onBackPressed();
        } else {
            showToast("再按一次退出程序");
        }
        lastPressedBackTime = System.currentTimeMillis();
    }
}
